#!/usr/bin/python3
"""
Configure yellowdog updater modified (YUM)

The stage currently supports configuring http_caching in YUM config and
locales in langpacks plugin. If the config files don't exist, they
are created.
"""
import os
import sys
import iniparse

import osbuild.api


SCHEMA = r"""
"additionalProperties": false,
"description": "YUM configuration.",
"properties": {
  "config": {
    "type": "object",
    "additionalProperties": false,
    "description": "YUM global configuration.",
    "properties": {
      "http_caching": {
        "type": "string",
        "enum": ["all", "packages", "lazy:packages", "none"],
        "description": "Determines how upstream HTTP caches are instructed to handle any HTTP downloads that YUM does."
      }
    }
  },
  "plugins": {
    "additionalProperties": false,
    "type": "object",
    "description": "YUM plugins configuration",
    "properties": {
      "langpacks": {
        "additionalProperties": false,
        "type": "object",
        "description": "'langpacks' YUM plugin configuration",
        "minProperties": 1,
        "properties": {
          "locales": {
            "type": "array",
            "minItems": 1,
            "description": "list of locales for YUM",
            "items": {
              "type": "string"
            }
          }
        }
      }
    }
  }
}
"""


def configure_plugins(tree, plugins_options):
    for plugin, plugin_options in plugins_options.items():
        plugin_conf_path = f"{tree}/etc/yum/pluginconf.d/{plugin}.conf"
        plugin_conf = iniparse.SafeConfigParser()

        try:
            with open(plugin_conf_path, "r") as f:
                plugin_conf.readfp(f)
        except FileNotFoundError:
            print(f"Warning: {plugin} configuration file '{plugin_conf_path}' does not exist, will create it.")

        # ensure that the pluginconf directory exists
        os.makedirs(f"{tree}/etc/yum/pluginconf.d/", exist_ok=True)

        for option, value in plugin_options.items():
            if option == "locales":
                if not plugin_conf.has_section("main"):
                    plugin_conf.add_section("main")

                locales = ", ".join(value)

                plugin_conf.set("main", "langpack_locales", locales)
            else:
                # schema does not allow any additional properties, but keeping this for completeness
                print(f"Error: unknown property {option} specified for {plugin} plugin.")
                return 1

        with open(plugin_conf_path, "w") as f:
            plugin_conf.write(f)

    return 0


def main(tree, options):
    config_options = options.get("config")
    plugins_options = options.get("plugins", {})

    yum_config_path = f"{tree}/etc/yum.conf"
    yum_config = iniparse.SafeConfigParser()

    if config_options:
        try:
            with open(yum_config_path, "r") as f:
                yum_config.readfp(f)
        except FileNotFoundError:
            print(f"Warning: YUM configuration file '{yum_config_path}' does not exist, will create it.")

        # only global options from the [main] section are supported
        if not yum_config.has_section("main"):
            yum_config.add_section("main")

        for option, value in config_options.items():
            yum_config.set("main", option, value)

        with open(yum_config_path, "w") as f:
            yum_config.write(f)

    if configure_plugins(tree, plugins_options):
        return 1

    return 0


if __name__ == '__main__':
    args = osbuild.api.arguments()
    r = main(args["tree"], args["options"])
    sys.exit(r)
